/*
 * @: 
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2022-03-10 14:16:15
 * @LastEditors: ziwei
 * @LastEditTime: 2022-03-11 14:32:19
 */
(function (ready) {
  if(document.readyState ==='complete'||document.readyState == 'interactive'){
    ready()
  }else{
    document.addEventListener('readystatechange',()=>{
      if(document.readyState == 'complete'){
        ready()
      }
    })
  }
})(function perf() {
  const data = {
    FP:0,//首次绘制
    FCP:0,//首次内容绘制
    LCP:0,//最大内容绘制
    FIP:0,//用户首次交互延迟
    CLS:0,//总布局偏移
  }
  //如果观察者观察到了指定类型的性能条目，就执行回调
  new PerformanceObserver(function (entryList) {
    let entries = entryList.getEntries();
    entries.forEach(entry=>{
      if(entry.startTime > data.LCP){
        console.log('记录LCP',(data.LCP = entry.startTime));
      }
      // if(entry.name === 'first-paint'){
      //   //首次绘制开始的事件
      //   data.FP = entry.startTime
      //   console.log('记录FP',data.FP);
      // }else if(entry.name === 'first-contentful-paint'){
      //   data.FCP = entry.startTime
      //   console.log('记录FCP',data.FCP);
      // }
    })
  }).observe({type:'largest-contentful-paint',buffered:true});

  new PerformanceObserver(function (entryList) {
    let entries = entryList.getEntries();
    entries.forEach(entry=>{
      //首次用户交互 开始处理的时间减去 开始交互的时间 就是首次交互延迟的时间
     const FID = entry.processingStart - entry.startTime;
     console.log("FID",FID,entry);
    })
  }).observe({type:'first-input',buffered:true});

  new PerformanceObserver(function (entryList) {
    let entries = entryList.getEntries();
    entries.forEach(entry=>{
      data.CLS += entry.value;
      console.log("CLS：",data.CLS);
    })
  }).observe({type:'layout-shift',buffered:true});
})
